//
//  BrowserAppDelegate.m
//  Browser
//
//  Created by Scott A. Guyer on 9/8/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "EVEApi.h"
#import "BrowserViewController.h"
#import "defs.h"

@implementation BrowserViewController


@synthesize toolbar, webView, delegate, statusView, activityView, statusLabel, reloadButton;


- (void) showError:(NSString*)msg 
{
	UIAlertView* a = [[UIAlertView alloc] initWithTitle:@"Web Error" 
												message:msg
											   delegate:nil 
									  cancelButtonTitle:@"OK" 
									  otherButtonTitles:nil];
	[a show];
	[a release];	
}

/*
 Implement loadView if you want to create a view hierarchy programmatically
- (void)loadView {
}
 */

- (void)viewDidAppear:(BOOL)animated
{
	if ( ! loggedIn )
		[self reloadAction:self];
}

- (void)viewDidLoad {
	[super viewDidLoad];
	
	loggedIn = NO;
	
	[webView setDelegate:self];
	[webView setDetectsPhoneNumbers:NO];
	
	//findButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(findAction:) ];
	findButton = [[UIBarButtonItem alloc] initWithTitle:@"Get Keys" 
												  style:UIBarButtonItemStyleBordered 
												 target:self 
												 action:@selector(findAction:)];
	
	statusButton = [[UIBarButtonItem alloc] initWithCustomView:statusView];	
	NSArray* barItems = [NSArray arrayWithObjects:findButton, statusButton, nil];	
	[toolbar setItems:barItems animated:NO];
	
	[findButton setEnabled:NO];
	[activityView stopAnimating];
}


- (void) clearCookies:(NSURL*)url 
{
	NSHTTPCookieStorage* jar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
	NSArray* cookies = [jar cookiesForURL:url];
	for ( NSHTTPCookie* c in cookies )
	{
		[jar deleteCookie:c];
	}
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if ( buttonIndex == 1 )
	{
		[self clearCookies:[NSURL URLWithString:@"http://myeve.eve-online.com/api/default.asp"]];
		loggedIn = NO;
		[self reloadAction:self];
	}
}




- (IBAction) reloadAction:(id) sender
{
	NSURL* url = [NSURL URLWithString:@"http://myeve.eve-online.com/api/default.asp"];
	
	if ( loggedIn )
	{
		UIAlertView* a = [[UIAlertView alloc] initWithTitle:@"Notice" 
													message:@"If you continue, this will erase your cookies and reload the EVE API Key login page." 
												   delegate:self 
										  cancelButtonTitle:@"Cancel" 
										  otherButtonTitles:@"Continue",nil];
		[a show];
		[a release];
		return;
	}
	
	NSURLRequest* req = [NSURLRequest requestWithURL:url
										 cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
									 timeoutInterval:30];	
	[webView loadRequest:req];	
	
	if ( response )
		response = nil;

	if ( receivedData != nil )
	{
		[receivedData release];
		receivedData = nil;
	}
	
	[reloadButton setEnabled:NO];
}


- (NSString*) getApiKeyFrom:(NSString*)html
{
	NSRange r = [html rangeOfString:@"API Key: "];
	if ( r.location == NSNotFound )
	{
		return nil;
	}
	
	r.location += r.length;
	r.length = 64;
	
	NSString* key = [html substringWithRange:r];	
	
	return key;
}


- (NSString*) getUserIdFrom:(NSString*)html
{
	NSRange b = [html rangeOfString:@"User ID: "];
	if ( b.location == NSNotFound )
	{
		return nil;
	}

	b.location += b.length;
	b.length = [html length] - b.location - 1;
	
	NSCharacterSet* aSet = [NSCharacterSet characterSetWithCharactersInString:@" \t\n<"];
	NSRange e = [html rangeOfCharacterFromSet:aSet options:0 range:b];
	
	NSRange uRange;
	uRange.location = b.location;
	uRange.length = e.location - b.location;
	
	NSString* uid = [html substringWithRange:uRange];
	
	return uid;
}



- (IBAction) findAction:(id) sender
{
	if ( receivedData == nil )
		return;
		
	NSString* html = [[NSString alloc] initWithData:receivedData encoding:NSISOLatin1StringEncoding];
	
	userId = [self getUserIdFrom:html];
	apiKey = [self getApiKeyFrom:html];

	[html release];	
	
	if ( userId != nil )
		[delegate setUserId:userId];
	
	if ( apiKey != nil )
		[delegate setApiKey:apiKey];
	
	[self.navigationController popViewControllerAnimated:YES];
}



- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	NSLog(@"%s Req:%@ Type:%d", __FUNCTION__, [request URL], navigationType);	
	
	if ( [[[request URL] absoluteString] hasPrefix:@"http://myeve.eve-online.com/api/default.asp?sid="] && (navigationType == UIWebViewNavigationTypeFormSubmitted) )
	{
		NSURLRequest* req = [NSURLRequest requestWithURL:[request URL]
											 cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
										 timeoutInterval:30];
		
		NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
		if ( conn == nil )
		{
			[self showError:@"Unable to load URL"];
		}
		else
		{
			if ( receivedData != nil )
				[receivedData release];
			
			receivedData = [[NSMutableData data] retain];
			[reloadButton setEnabled:NO];
		}
		
		return NO;
	}
	
	
	return YES;
}


- (void)webViewDidFinishLoad:(UIWebView *)webView
{
	NSLog(@"%s", __FUNCTION__);	
	[activityView stopAnimating];
	[statusLabel setText:@""];
	[reloadButton setEnabled:YES];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
	NSLog(@"%s", __FUNCTION__);
	[activityView startAnimating];
	[statusLabel setText:@"Loading …"];
	[reloadButton setEnabled:NO];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
	NSLog(@"%s %@", __FUNCTION__, [error localizedDescription]);

	if ( [[error domain] isEqualToString:@"WebKitErrorDomain"] && ([error code] == 102) )
		return;

	if ( [[error domain] isEqualToString:@"NSURLErrorDomain"] && ([error code] == -999) )
		return;

	
	[self showError:[error localizedDescription]];

	[activityView stopAnimating];
	[statusLabel setText:@""];
	[reloadButton setEnabled:YES];	
}



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)r
{
    // this method is called when the server has determined that it
    // has enough information to create the NSURLResponse
	
    // it can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    // receivedData is declared as a method instance elsewhere
    [receivedData setLength:0];
	if ( response != nil )
	{
		[response release];
		response = nil;
	}
	
	response = [r copy];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [receivedData appendData:data];
}


- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];
	receivedData = nil;
	
	loggedIn = NO;
	[reloadButton setEnabled:YES];
	
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
	
	[self showError:[error localizedDescription]];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
	
	[webView loadData:receivedData MIMEType:[response MIMEType] textEncodingName:[response textEncodingName] baseURL:[response URL]];
	
	[findButton setEnabled:YES];
	[reloadButton setEnabled:YES];
	loggedIn = YES;
	
    // release the connection, and the data object
    [connection release];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}




- (void)dealloc 
{
	WIPE( webView)
	WIPE( toolbar)
	WIPE( statusView)
	WIPE( activityView)
	WIPE( statusLabel)
	WIPE( findButton)
	WIPE( statusButton)
	WIPE( receivedData)
	WIPE( response)

	[super dealloc];
}

@end
